package com.meiyuetao.myt.sale.web.action;

import java.util.Date;
import java.util.List;
import java.util.Map;

import lab.s2jh.core.annotation.MetaData;
import lab.s2jh.core.security.AuthContextHolder;
import lab.s2jh.core.service.BaseService;
import lab.s2jh.core.util.DateUtils;
import lab.s2jh.core.web.view.OperationResult;

import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.rest.HttpHeaders;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.common.collect.Maps;
import com.meiyuetao.myt.core.constant.VoucherStateEnum;
import com.meiyuetao.myt.core.constant.VoucherTypeEnum;
import com.meiyuetao.myt.core.service.VoucherNumGenerateService;
import com.meiyuetao.myt.core.web.MytBaseController;
import com.meiyuetao.myt.sale.entity.SaleReturn;
import com.meiyuetao.myt.sale.entity.SaleReturnDetail;
import com.meiyuetao.myt.sale.service.SaleReturnService;

@MetaData("SaleReturnController")
public class SaleReturnController extends MytBaseController<SaleReturn, Long> {

    @Autowired
    private SaleReturnService saleReturnService;
    @Autowired
    private VoucherNumGenerateService voucherNumGenerateService;

    @Override
    protected BaseService<SaleReturn, Long> getEntityService() {
        return saleReturnService;
    }

    @Override
    protected void checkEntityAclPermission(SaleReturn entity) {
        // TODO Add acl check code logic
    }

    @Override
    protected void setupDetachedBindingEntity(Long id) {
        bindingEntity = getEntityService().findDetachedOne(id, "saleReturnDetails");
    }

    public void prepareBpmNew() {
        bindingEntity = new SaleReturn();
        bindingEntity.setVoucher(voucherNumGenerateService.getVoucherNumByType(VoucherTypeEnum.TH));
        bindingEntity.setVoucherDate(new Date());
        bindingEntity.setVoucherUser(getLogonUser());
        bindingEntity.setVoucherDepartment(getLogonUser().getDepartment());
    }

    @MetaData("创建初始化")
    public HttpHeaders bpmNew() {
        return buildDefaultHttpHeaders("bpmInput");
    }

    @MetaData("退换货单新建")
    public HttpHeaders bpmSave() {

        Map<String, Object> variables = Maps.newHashMap();
        String submitToAudit = this.getParameter("submitToAudit");
        if (BooleanUtils.toBoolean(submitToAudit)) {
            bindingEntity.setLastOperationSummary("提交:" + DateUtils.formatTime(new Date()));
            bindingEntity.setSubmitDate(new Date());
        }

        List<SaleReturnDetail> saleReturnDetails = bindingEntity.getSaleReturnDetails();
        for (SaleReturnDetail saleReturnDetail : saleReturnDetails) {
            saleReturnDetail.setSaleReturn(bindingEntity);
        }
        if (bindingEntity.isNew()) {
            // 销售单页面如果没有输入“关联订单号”，则提交处理逻辑中兼容处理取凭证号赋值给“关联订单号”
            if (StringUtils.isBlank(bindingEntity.getReferenceVoucher())) {
                bindingEntity.setReferenceVoucher(bindingEntity.getVoucher());
            }
            saleReturnService.bpmCreate(bindingEntity, variables);
            setModel(OperationResult.buildSuccessResult("退(换)货单创建完成，并同步启动处理流程", bindingEntity));
        } else {
            saleReturnService.bpmUpdate(bindingEntity, this.getRequiredParameter("taskId"), variables);
            setModel(OperationResult.buildSuccessResult("退(换)货单任务提交完成", bindingEntity));
        }
        return buildDefaultHttpHeaders();
    }

    @MetaData("一线审核")
    public HttpHeaders bpmLevel1Audit() {
        Map<String, Object> variables = Maps.newHashMap();
        variables.put("auditLevel1Time", new Date());
        variables.put("auditLevel1User", AuthContextHolder.getAuthUserPin());
        Boolean auditLevel1Pass = new Boolean(getRequiredParameter("auditLevel1Pass"));
        variables.put("auditLevel1Pass", auditLevel1Pass);
        variables.put("auditLevel1Explain", getParameter("auditLevel1Explain"));
        bindingEntity.setLastOperationSummary(bindingEntity.buildLastOperationSummary("审核"));
        if (!auditLevel1Pass) {
            bindingEntity.setSubmitDate(null);
        }
        saleReturnService.bpmUpdate(bindingEntity, this.getRequiredParameter("taskId"), variables);
        setModel(OperationResult.buildSuccessResult("退(换)货单一线审核完成", bindingEntity));
        return buildDefaultHttpHeaders();
    }

    @Override
    @MetaData("保存")
    public HttpHeaders doSave() {
        if (bindingEntity.isNew()) {
            List<SaleReturnDetail> saleReturnDetails = bindingEntity.getSaleReturnDetails();
            for (SaleReturnDetail saleReturnDetail : saleReturnDetails) {
                saleReturnDetail.setSaleReturn(bindingEntity);
            }
        }
        if (VoucherStateEnum.DRAFT.equals(bindingEntity.getVoucherState())) {
            if (VoucherStateEnum.POST.name().equals(getParameter("voucherState"))) {
                bindingEntity.setVoucherState(VoucherStateEnum.POST);
            }
        }
        saleReturnService.save(bindingEntity);
        setModel(OperationResult.buildSuccessResult("数据保存成功", bindingEntity));
        return buildDefaultHttpHeaders();
    }

    @Override
    @MetaData("删除")
    public HttpHeaders doDelete() {
        return super.doDelete();
    }

    @Override
    @MetaData("查询")
    public HttpHeaders findByPage() {
        return super.findByPage();
    }

    @MetaData("行项数据")
    public HttpHeaders saleReturnDetails() {
        List<SaleReturnDetail> saleReturnDetails = bindingEntity.getSaleReturnDetails();
        setModel(buildPageResultFromList(saleReturnDetails));
        return buildDefaultHttpHeaders();
    }

    public Map<String, String> getReferenceSourceMap() {
        return this.findMapDataByDataDictPrimaryKey("MYT_SALE_DELIVERY_ORDER_SOURCE");
    }
}